<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      :btn-list="fullInfo.btnList"
    >
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('use_information') }}</p>
        </div>
        <div class="model-panel-body">
          <BasicInformation :info="infoList"></BasicInformation>
        </div>
      </div>

      <div class="model-panel">
        <div class="model-panel-title">
          <Tooltip :text="$t('detailInfo')" />
        </div>
        <div class="model-panel-body">
          <!-- 条件栏 -->
          <NewPageFilter
            v-model:query="filterInfo.query"
            :filter-btn="filterInfo.list"
          >
            <template v-slot:filter-removeProduct>
              <el-button :disabled="!canDeleteProduct" @click="removeProduct()"
                >删除产品</el-button
              >
            </template>
            <template v-slot:filter-oneKeyBatch>
              <el-button @click="oneKeyBatch">智能推荐</el-button>
            </template>
          </NewPageFilter>
          <div class="flex_full_item">
            <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
              <!-- 表格 -->
              <PageTable
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                rowKey="uuid"
                :summary="true"
                :summary-field-list="tableInfo.summaryFieldList"
                :tab-index="true"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :row-class-name="tableRowClassName"
                :isDynamic="true"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-qty="scope">
                  <!--<el-form-item
                      v-if="
                        scope.row.codeType === 1 || scope.row.codeType === 4
                      "
                      class="margin-bottom"
                    >-->
                  <div class="page-table-input-number-wrapper">
                    <div class="page-table-input-number-left">
                      <div class="page-table-input-number-item">
                        <el-form-item
                          :prop="`data.${scope.$index}.largeUnitQty`"
                          :rules="
                            scope.$index >= 0
                              ? [
                                  {
                                    validator: $validate.positiveAndZero,
                                    trigger: 'blur',
                                  },
                                ]
                              : []
                          "
                        >
                          <el-input-number
                            v-model.lazy="scope.row.largeUnitQty"
                            style="width: 100%; margintop: 18px"
                            clearable
                            controls-position="right"
                            :precision="
                              scope.row.qtyOperateMode === 0 ||
                              scope.row.qtyOperateMode === 2
                                ? 0
                                : systemConfig.qty_show_precision
                            "
                            :min="0"
                            :max="largeMax(scope.row)"
                            @change="
                              changeLarge(
                                $event,
                                scope.row,
                                `data.${scope.$index}.largeUnitQty`
                              )
                            "
                          />
                        </el-form-item>
                        <div class="page-table-input-number-item-unite">
                          {{ scope.row.unitName }}
                        </div>
                      </div>
                      <div
                        v-if="
                          scope.row.unitConvertCoefficient > 1 &&
                          scope.row.qtyOperateMode === 2
                        "
                        class="page-table-input-number-item"
                      >
                        <el-form-item>
                          <el-input-number
                            v-model.lazy="scope.row.smallUnitQty"
                            style="width: 100%; margintop: 18px"
                            clearable
                            controls-position="right"
                            :precision="0"
                            :min="0"
                            :max="smallMax(scope.row)"
                          />
                        </el-form-item>
                        <div class="page-table-input-number-item-unite">
                          {{ scope.row.calcUnitName }}
                        </div>
                      </div>
                    </div>
                    <div
                      v-if="scope.row.qtyOperateMode === 2"
                      class="page-table-input-number-right"
                    >
                      {{ $fn.qtyFormatter(scope.row.qty) }}
                    </div>
                  </div>
                  <!--</el-form-item>
                    <span
                      v-else-if="
                        scope.row.codeType === 2 || scope.row.codeType === 3
                      "
                      >{{ $fn.qtyFormatter(scope.row.qty) }}</span
                    >-->
                </template>
              </PageTable>
            </el-form>
          </div>
        </div>
      </div>
    </NewFullScreen>
    <select-detail-depot-storage
      v-if="selectDepotStorageInfo.visible"
      v-model:show-dialog="selectDepotStorageInfo.visible"
      v-model:query="selectDepotStorageInfo.query"
      :order-id="id"
      :depot-id="selectDepotStorageInfo.depotId"
      :exclude-product-ids="selectDepotStorageInfo.excludeProductIds"
      :exclude-query-list="selectDepotStorageInfo.excludeQueryList"
      :left-table-key="selectDepotStorageInfo.tableKey"
      :show-price="$permission('useAudit:price')"
      @callback="selectDepotStorageCallBack"
    />
  </div>
</template>

<script setup name="useApplicationDownShelfTask">
import SelectDetailDepotStorage from './selectProduct'
import { getRrgUserAll } from '@/api/base.js'
import {
  getUseApplication,
  exportUseApplication,
  printUseApplication,
  getUseApplicationDetailByOrderId,
} from '@/api/use'
import { createWmsExportOrder, smartRecommendation } from '@/api/wms'

import { getCustomizeSetting } from '@/api/customize'
import moment from 'moment'
import _ from 'lodash'

const { proxy } = getCurrentInstance()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: () => {
      return ''
    },
  },
  id: {
    type: [Number, String],
  },
})
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const selectDepotStorageInfo = ref({
  //库存产品
  visible: false,
  depotId: '',
  excludeProductIds: [],
  excludeQueryList: [], //库存产品左侧过滤配置
  query: {
    productId: { queryType: 'IN', queryCategory: 'AND', value: '' },
    isConsignBusiness: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: '',
    },
  },
  tableKey:
    'useApplicationOrderModifyDownShelfTaskProduct-com.slip.spd.entity.vo.stock.DepotStockVO',
})
const infoList = ref({
  ref: null,
  data: {},
  fieldList: [
    { label: '申请单号', value: 'orderNo', type: 'text' },
    { label: '领用人', value: 'createUserName', type: 'text' },
    { label: '领用部门', value: 'deptName', type: 'text' },
    { label: '领入仓库', value: 'depotName', type: 'text' },
    { label: '领出仓库', value: 'exportDepotName', type: 'text' },
    {
      label: '是否寄售业务',
      value: 'isConsignBusinessValue',
      type: 'text',
      show:
        props.id &&
        proxy.$store.state.permission.systemConfig.is_consign_business == 1,
    },
  ],
})
const listTypeInfo = ref({
  userList: [],
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
  },
  list: [
    { type: 'button', label: '添加产品', event: addProduct },
    { type: 'slot', value: 'removeProduct' },
    { type: 'slot', value: 'oneKeyBatch' },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  isSysGroup: true, //新增修改页是否有后端合并
  sysGroup: [], //新增修改页后端合并项
  selections: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '删除',
        event: removeProduct,
        show: true,
        popconfirmText: '删除后将改变数据,是否继续？',
      },
    ],
  },
})
const fullInfo = ref({
  btnList: [
    { label: '提交', event: _export, show: true },
    { label: '导出excel', event: exportExcel, show: false },
    { label: '打印', event: print, show: false },
  ],
})
const productInfo = ref({
  ids: [],
  data: [],
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    proxy.$emit('update:visible', val) // 更新父组件visible
  },
})
const canDeleteProduct = computed(() => {
  return tableInfo.value.selections.length
})
const canOnKeyBatchProduct = computed(() => {
  let list = tableInfo.value.data.filter(
    (item) => item.codeType === 1 || item.codeType === 4
  )
  return list.length
})
watch(
  () => props.visible,
  (val) => {
    showDialog.value = val
  },
  { immediate: true }
)
watch(
  () => tableInfo.value.data,
  (val) => {
    if (val.length) {
      val.forEach((row) => {
        let smallUnitQty = parseFloat(row.smallUnitQty || 0)
        let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
        let largeUnitQty = parseFloat(row.largeUnitQty || 0)
        let calcQty = proxy.$fn.accAdd(
          proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
          smallUnitQty
        )
        let qty = proxy.$fn.qtyFormatter(
          proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
        )
        row['calcQty'] = calcQty
        row['qty'] = qty
        row.sumAmount = proxy.$fn.accDiv(
          proxy.$fn.accMul(calcQty, parseFloat(row.price)),
          unitConvertCoefficient
        )
      })
    }
  },
  { deep: true }
)

//获取人员列表
function getUserList() {
  let params = {
    sort: 'create_time desc',
  }
  getRrgUserAll(params).then((res) => {
    if (res && res.success) {
      let arr = [{ key: '暂不选择', value: '-2', userName: '' }]
      if (res.data && res.data.length) {
        let data = res.data.map((item) => {
          return {
            key: item.name,
            value: item.id.toString(),
            userName: item.userName,
          }
        })
        listTypeInfo.value.userList = arr.concat(data)
      }
    }
  })
}
function largeMax(row) {
  if (row.qtyOperateMode === 2) {
    return parseInt(row.stockAvailableCalcQty / row.unitConvertCoefficient)
  } else {
    return row.stockAvailableQty
  }
}
function smallMax(row) {
  let largeUnitQty = parseInt(
    row.stockAvailableCalcQty / row.unitConvertCoefficient
  )
  if (largeUnitQty === 0 || row.largeUnitQty === largeUnitQty) {
    return parseInt(row.stockAvailableCalcQty % row.unitConvertCoefficient)
  } else {
    return row.unitConvertCoefficient - 1
  }
}
function changeLarge(e, row, str) {
  proxy.$refs.tableForm.clearValidate(str)
  let largeUnitQty = parseInt(
    row.stockAvailableCalcQty / row.unitConvertCoefficient
  )
  if (row.qtyOperateMode === 2 && row.unitConvertCoefficient > 1) {
    if (largeUnitQty > 0 && e === largeUnitQty) {
      let smallUnitQty = parseInt(
        row.stockAvailableCalcQty % row.unitConvertCoefficient
      )
      if (row.smallUnitQty > smallUnitQty) {
        row.smallUnitQty = smallUnitQty
      }
    }
  }
}
function tableRowClassName({ row = undefined }) {
  if (row.isChoice) {
    return 'success-row'
  } else {
    return ''
  }
}

function ifRenderValue() {
  return tableInfo.value.isSysGroup
}
function getMain() {
  getUseApplication(props.id).then((resp) => {
    if (resp && resp.success) {
      infoList.value.data = resp.data
      selectDepotStorageInfo.value.depotId = resp.data.exportDepotId
    }
  })
  filterInfo.value.query.queryMap.orderId.value = props.id ////
  getList()
}
function getList() {
  //修改请求明细信息
  getUseApplicationDetailByOrderId(props.id).then((resp) => {
    if (resp && resp.success && resp.data.length) {
      //获取产品ID
      let productIds = []
      resp.data.map((item) => {
        //当可出库数量小于等于0的时候，产品不再添加到弹框搜索列表中
        if (item.qty > item.preExportQty) {
          productIds.push(item.productId)
        }
      })
      productInfo.value.ids = String(productIds)
      productInfo.value.data = resp.data
    }
  })
}
function getCustomize() {
  let param = {
    tableKey:
      'useApplicationOrderRatifyDownShelfTaskModify-com.slip.spd.entity.vo.use.UseExportOrderDetailVO',
  }
  tableInfo.value.isSysGroup = false
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      for (let key in data.detail) {
        if (data.detail[key].sysGroupLevel > 0) {
          tableInfo.value.isSysGroup = true
        }
      }
      filterInfo.value.query.customizeUserVO = data
      getDeoptCustomize()
    }
  })
}
function getDeoptCustomize() {
  //库存产品弹窗左侧配置
  let param = {
    tableKey:
      'useApplicationOrderModifyDownShelfTaskProduct-com.slip.spd.entity.vo.stock.DepotStockVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      let arr = []
      if (tableInfo.value.isSysGroup) {
        for (let key in data.detail) {
          if (data.detail[key].sysGroupLevel > 0) {
            arr.push({
              columnName: data.detail[key].columnName,
              asTbName: data.detail[key].asTbName,
              key: key,
            })
          }
        }
      } else {
        arr.push({
          columnName: data.detail.id.columnName,
          asTbName: data.detail.id.asTbName,
          key: 'depotStockId',
        })
      }
      tableInfo.value.sysGroup = arr
      if (props.id) {
        getMain()
      }
    }
  })
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function addProduct() {
  let excludeQueryList = []
  tableInfo.value.data.forEach((item) => {
    let key = []
    if (tableInfo.value.sysGroup.length) {
      tableInfo.value.sysGroup.forEach((row) => {
        let obj = {}
        obj.columnName = row.columnName
        obj.asTbName = row.asTbName
        obj.value = item[row.key]
        key.push(obj)
      })
    }
    excludeQueryList.push(key)
  })
  selectDepotStorageInfo.value.excludeQueryList = excludeQueryList //库存产品左侧过滤配置
  selectDepotStorageInfo.value.query.isConsignBusiness.value =
    infoList.value.data.isConsignBusiness
  selectDepotStorageInfo.value.visible = true
}
async function selectDepotStorageCallBack(rows = []) {
  //库存产品返回
  tableInfo.value.data = rows.concat(tableInfo.value.data)
}
function _export() {
  if (tableInfo.value.data.length === 0) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '出库明细不能为空',
    })
    return
  } else {
    const qtyZero = tableInfo.value.data
      .filter((item) => !item.qty || item.qty === 0)
      .map((item) => item.commonName)

    if (qtyZero.length) {
      proxy.$alert(`产品【${qtyZero}】出库数量不能为0`, '操作提示', {
        confirmButtonText: '确定',
      })
      return
    }
    let newDatas = {
      orderSourceId: infoList.value.data.id,
      orderSourceNo: infoList.value.data.orderNo,
      orderSourceType: 19,
      type: 1,
      isFromSpdBusiness: true,
      ...infoList.value.data,
      deptId: infoList.value.data.exportDeptId,
      depotId: infoList.value.data.exportDepotId,
      storeDeptId: infoList.value.data.deptId,
      storeDepotId: infoList.value.data.depotId,
      mergeDetails: proxy.$fn.filterBlacklist(tableInfo.value.data),
    }
    let expire = validateExpire(tableInfo.value.data)
    if (expire) {
      proxy
        .$confirm(expire + ',是否继续?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          dangerouslyUseHTMLString: true,
        })
        .then(() => {
          createWmsExportOrder(newDatas).then((resp) => {
            if (resp && resp.success) {
              showDialog.value = false
              proxy.$emit('returnModify')
            }
          })
          return
        })
        .catch(() => {
          return
        })
    } else {
      createWmsExportOrder(newDatas).then((resp) => {
        if (resp && resp.success) {
          showDialog.value = false
          proxy.$emit('returnModify')
        }
      })
      return
    }
  }
}
function validateExpire(list = []) {
  let currentDate = moment().format('YYYY-MM-DD')
  let msg = ''
  list.forEach((item, index) => {
    if (item.validityDate && moment(item.validityDate).isBefore(currentDate)) {
      msg = msg + `第【${index + 1}】行产品【${item.commonName}】已过期，<br>`
    }
  })
  return msg
}

//删除产品
function removeProduct(row = undefined) {
  if (row && Object.keys(row).length > 1) {
    tableInfo.value.data = tableInfo.value.data.filter((item) => item !== row)
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.value.data = tableInfo.value.data.filter((row) => {
          return !tableInfo.value.selections.includes(row)
        })
      })
  }
  selectDepotStorageInfo.value.excludeProductIds = tableInfo.value.data.map(
    (item) => item.productId
  )
}

function oneKeyBatch() {
  let params = {
    orderSourceId: infoList.value.data.id,
    orderSourceNo: infoList.value.data.orderNo,
    orderSourceType: 19,
    type: 1,
    isFromSpdBusiness: true,
    ...infoList.value.data,
    deptId: infoList.value.data.exportDeptId,
    depotId: infoList.value.data.exportDepotId,
    storeDeptId: infoList.value.data.deptId,
    storeDepotId: infoList.value.data.depotId,
    mergeDetails: proxy.$fn.filterBlacklist(tableInfo.value.data),
  }
  let sysGroup = tableInfo.value.sysGroup
  smartRecommendation(params).then((res) => {
    if (res && res.success) {
      let data = res.data
      if (data && data.length) {
        data.forEach((item) => {
          let key = []
          if (sysGroup.length) {
            sysGroup.forEach((row) => {
              let obj = {}
              obj.columnName = row.columnName
              obj.asTbName = row.asTbName
              obj.value = item[row.key]
              key.push(obj)
            })
          }
          item.key = JSON.stringify(key)
        })
        let groupData = _.groupBy(data, (item) => {
          return item.key
        })
        let groupDataValue = Object.values(groupData)
        let newArr = []
        groupDataValue.forEach((row) => {
          let arr = proxy.$fn.deepClone(row)
          let obj = arr[0]
          let calcQty = 0
          let largeUnitQty = 0
          let smallUnitQty = 0
          let sumAmount = 0
          let stockAvailableCalcQty = 0
          let groupConcatDepotStockIds = []
          arr.forEach((item) => {
            largeUnitQty = proxy.$fn.accAdd(
              largeUnitQty,
              item.largeUnitQty || 0
            )
            smallUnitQty = proxy.$fn.accAdd(
              smallUnitQty,
              item.smallUnitQty || 0
            )
            sumAmount = proxy.$fn.accAdd(sumAmount, item.sumAmount || 0)
            calcQty = proxy.$fn.accAdd(calcQty, item.calcQty || 0)
            stockAvailableCalcQty = proxy.$fn.accAdd(
              stockAvailableCalcQty,
              item.stockAvailableCalcQty || 0
            )
            groupConcatDepotStockIds.push(item.depotStockId)
          })
          obj['largeUnitQty'] = largeUnitQty
          obj['smallUnitQty'] = smallUnitQty
          obj['calcQty'] = calcQty
          obj['stockAvailableCalcQty'] = stockAvailableCalcQty
          obj['sumAmount'] = sumAmount
          let qty = proxy.$fn.accDiv(calcQty, obj.unitConvertCoefficient)
          let stockAvailableQty = proxy.$fn.accDiv(
            stockAvailableCalcQty,
            obj.unitConvertCoefficient
          )
          obj['qty'] = qty
          obj['stockAvailableQty'] = stockAvailableQty
          obj['details'] = row
          obj['groupConcatDepotStockIds'] = groupConcatDepotStockIds.toString()
          newArr.push(obj)
        })
        tableInfo.value.data = newArr
      }
    }
  })
}

//导出excel
function exportExcel() {
  exportUseApplication(infoList.value.data.id).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
//打印
function print() {
  printUseApplication(infoList.value.data.id).then((resp) => {
    if (resp && resp.success) {
      proxy.$print.printOrder(resp.data)
    }
  })
}

let obj = {
  orderNo: {
    label: '单号',
    value: 'orderNo',
    componentType: 'input',
    show: false,
    // type: 'slot',
    hidden: true,
  },
  qty: {
    label: '出库数量',
    value: 'qty',
    type: 'slot',
    componentType: 'number',
    width: '250px',
    formatter: proxy.$fn.qtyFormatter,
    hidden: true,
  },
  applicationQty: {
    label: '申请数量',
    value: 'applicationQty',
    type: 'column',
    formatter: proxy.$fn.qtyFormatter,
    componentType: 'number',
    hidden: true,
  },
  availableQty: {
    label: '可出库数量',
    value: 'availableQty',
    type: 'column',
    formatter: proxy.$fn.qtyFormatter,
    componentType: 'number',
    hidden: true,
  },
  price: {
    label: '单价',
    value: 'price',
    minWidth: '150px',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('useAudit:price'),
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('useAudit:price'),
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    permission: !proxy.$permission('useAudit:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
  },
}
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getUserList()
getCustomize()
onMounted(() => {
  // formRefs.value = [proxy.$refs['tableForm'], infoList.value.ref]
  proxy.$nextTick(() => {
    if (!props.id) {
      infoList.value.fieldList = infoList.value.fieldList.filter(
        (item) => item.value !== 'orderNo'
      )
    }
  })
})
</script>

<style scoped></style>
